class ReviewsController < ApplicationController
  # GET /reviews
  # GET /reviews.json
  def index
    @review_type = ReviewType.includes(:rating_criterions).find(params[:review_type_id])
    @review_type.load_kpis
    
    @reviews = @review_type.reviews.includes(:ratings=>:rating_criterion).order(:created_at).reverse_order
  end

  # GET /reviews/new
  # GET /reviews/new.json
  def new
    @review_type = ReviewType.find(params[:review_type_id])
    @review = @review_type.reviews.build
  end

  # POST /reviews
  # POST /reviews.json
  def create
    build_review

    if @review.save
      flash[:notice]='Review was successfully created.'
      redirect_to review_type_reviews_url(@review.review_type)
    else
      render action: "new"
    end
  end

  private  
  def build_review
    @review_type = ReviewType.includes(:rating_criterions).find(params[:review_type_id])
    @review = @review_type.reviews.build(params[:review])
    use_default_title_if_blank
    
    @review_type.rating_criterions.each do |rating_criterion|
      rating=@review.ratings.build
      rating.rating_criterion=rating_criterion
      rating.rating_value=get_rating_value_Or_default params[rating_criterion.prefixed_name]
    end
  end

  def use_default_title_if_blank
    if(@review.title.blank?)
      @review.title="Untitled"
    end
  end

  def get_rating_value_Or_default(rating_value)
    rating_value.nil? ? 0 : rating_value
  end
end
